package com.lengxf.netty.config;

import com.lengxf.netty.enums.ChannelTypeEnum;
import io.netty.channel.Channel;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 通道管理
 */
public class ChannelContext {

    //channelId channel
    private static final Map<String, Channel> CHANNEL_HOLDER = new ConcurrentHashMap<>();

    //ip 通道类型
    private static final Map<String, ChannelTypeEnum> CHANNEL_TYPE = new ConcurrentHashMap<>();

    /**
     * 根据通道类型获取通道
     */
    public static List<Channel> getChannel(String type) {
        List<Channel> list = new ArrayList<>();
        ChannelTypeEnum channelTypeEnum = ChannelTypeEnum.getEnumByCode(type);
        CHANNEL_TYPE.forEach((k, v) -> {
            if (channelTypeEnum.equals(v)) {
                if (CHANNEL_HOLDER.containsKey(k)) {
                    list.add(CHANNEL_HOLDER.get(k));
                }
            }
        });
        return list;
    }

    /**
     * 管理通道
     */
    public static void saveChannel(String channelId, Channel channel) {
        CHANNEL_HOLDER.put(channelId, channel);
    }

    /**
     * 管理通道类型
     */
    public static void saveChannelType(String channelId, String type) {
        if (CHANNEL_TYPE.containsKey(channelId)) {
            return;
        }
        CHANNEL_TYPE.put(channelId, ChannelTypeEnum.getEnumByCode(type));
    }

    /**
     * 移除通道
     */
    public static void removeChannel(String channelId) {
        CHANNEL_HOLDER.remove(channelId);
        CHANNEL_TYPE.remove(channelId);
    }


}
